#include "RegionPanel.hpp"

RegionPanel::RegionPanel():Panel(0,0, 200, 120, Panel::Static){
    title.setPosition(5, 2);
    title.setString(10, sf::Color::White, sf::Text::Underlined, std::string("Regions"));
    add(&title);
    
    listContainer.setSize(198, 104);
    listContainer.setPosition(2, 16);
    listPanel.setSize(198, 0);
    listPanel.setPosition(0, 0);
    listContainer.add(&listPanel);
    
    add(&listContainer);
    trap(InterfaceEvent::LeftClick);
}

void RegionPanel::setRegionManager(EditorRegionManager* manager){
    regions.clear();
    regionManager = manager;
    listPanel.clear();
    while(regionLabels.size() > 0){
        Label* regionLabel = regionLabels.back();
        regionLabels.pop_back();
        delete regionLabel;
    }
    regionLabels.clear();
    
    for(unsigned short i = 0; i < regionManager->size; i++){
        if(regionManager->regions[i]){
            addRegion((EditorRegion*)regionManager->regions[i]);
        }
    }
}

void RegionPanel::addRegion(EditorRegion* region){
    regions.push_back(region);
    Label* regionLabel = new Label(0, 0, 10, sf::Color::White, 
            region->name + std::string(" ") + StringHelper::itos(region->width) + "x" + StringHelper::itos(region->height) +
            " at (" + StringHelper::itos(region->x) + "," + StringHelper::itos(region->y) + ")");
	region->regionLabel = regionLabel;

    listPanel.addBottom(regionLabel);
    listContainer.updateScrollView();
    regionLabels.push_back(regionLabel);
}

void RegionPanel::removeRegion(EditorRegion* region){
	for(int i = 0; i < regions.size(); i++){
		if(regions.at(i) == region){
			regions.erase(regions.begin() + i);
            regionLabels.erase(regionLabels.begin() + i);
			listPanel.remove(region->regionLabel);
			delete region->regionLabel;
			region->regionLabel = 0;
			redraw();
			break;
		}
	}
}

bool RegionPanel::trapped(InterfaceEvent* event){
    for(int i = 0; i < regionLabels.size(); i++){
        if(regionLabels.at(i) == event->source){
            raise(InterfaceEvent::Custom, regions.at(i));
            return true;
        }
    }
}

void RegionPanel::redraw(){
	listContainer.updateScrollView();
}